﻿using System;
using System.Globalization;
using System.ServiceModel;
using DevWeb.Biztalk.DeploymentSettings.DeploymentService.Contracts;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;

namespace DevWeb.BizTalk.DeploymentFramework.Tasks
{
    public class LogDeploymentTask:Task
    {
        [Required]
        public string ProjectName { get; set; }

        [Required]
        public string ProductId { get; set; }

        [Required]
        public string ProductUpgradeCode { get; set; }

        [Required]
        public string Version { get; set; }

        [Required]
        public string DeploymentType { get; set; }

        [Required]
        public string ServiceAddress { get; set; }


        public override bool Execute()
        {
            string logmsg =
                string.Format(
                    "User {4} called LogDeploymentTask for integration {0} with version : {1} (ProductId:{2}) (ProductUpgradeCode{3}) on date: {5}",
                    ProjectName, Version, ProductId, ProductUpgradeCode, System.Environment.UserName, DateTime.Now.ToString(CultureInfo.InvariantCulture));


            Log.LogMessage(MessageImportance.High, logmsg);



            return LogDeployment();
        }

        private bool LogDeployment()
        {
            Log.LogMessage(MessageImportance.High, string.Format("Setup Client   to {0}  ", ServiceAddress));

            var result = false;
            try
            {

            
            var binding = new WSHttpBinding();
            binding.Security.Mode = SecurityMode.None;
            var endpointaddress = new EndpointAddress(ServiceAddress.Trim());

            var client = ChannelFactory<IDeploymentSettingsService>.CreateChannel(binding, endpointaddress);
            var productupgragdecode = Guid.Parse(ProductUpgradeCode);
            var productid = Guid.Parse(ProductId);
            Environment = System.Environment.GetEnvironmentVariable("BTDFENV");
            Machinename = System.Environment.MachineName;
            Username = System.Environment.UserName;
            result = client.LogDeployment(Machinename, Username, DeploymentType, productid, productupgragdecode, Environment);
            Log.LogMessage(MessageImportance.High, "Log Succesfull");

            }
            catch (Exception ex)
            {

                Log.LogMessage(MessageImportance.High, string.Format("Error Occured \r\n {0}  ", ex.Message));
                result = false;
            }
            return result;
        }

        private string Environment { get; set; }

        private string Username { get; set; }

        private string Machinename { get; set; }
    }
}
